package com.ayou.healthmanagement.service.impl;

import com.ayou.healthmanagement.dto.PageDto;
import com.ayou.healthmanagement.dto.UserDto;
import com.ayou.healthmanagement.pojo.HealthUser;
import com.ayou.healthmanagement.utils.*;
import com.ayou.healthmanagement.utils.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ayou.healthmanagement.service.HealthUserService;
import com.ayou.healthmanagement.mapper.HealthUserMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Service
public class HealthUserServiceImpl extends ServiceImpl<HealthUserMapper, HealthUser>
    implements HealthUserService{

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private HealthUserMapper healthUserMapper;

    @Override
    public Result register(HealthUser healthUser) {
        //判断此号是否已经存在
        HealthUser user = healthUserMapper.selectOne(new QueryWrapper<HealthUser>().eq("user_phone", healthUser.getUserPhone()));
        if (user!=null){
            return Result.failure(ResultCode.DATA_ALREADY_EXISTED);
        }
        healthUser.setAvatar("https://edu-learn-bucket.oss-cn-hangzhou.aliyuncs.com/img_files/1712460465040.png");
        //md5密码加密
        healthUser.setPassword(MD5Utils.getPWD(healthUser.getPassword()));
        return Result.success(healthUserMapper.insert(healthUser));
    }

    @Override
    public Result login(HealthUser healthUser) {
//        System.out.println(healthUser);
        //校验验证码
        Object code = redisUtil.get("code");
        if (code!=null && code.equals(healthUser.getCode())){
            HealthUser user = healthUserMapper.selectOne(new QueryWrapper<HealthUser>()
                    .eq("user_phone", healthUser.getUserPhone())
                    .eq("password", MD5Utils.getPWD(healthUser.getPassword()))
                    .eq("user_role",healthUser.getUserRole()));
            if (user==null){
                return Result.failure(ResultCode.RESULE_DATA_NONE);
            }
            String token = JwtUtils.getJwtToken(String.valueOf(user.getId()), user.getUserPhone());
            //将token存入缓存
            redisUtil.set(user.getId()+"",token,1800);
            return Result.success(token);
        }
        return Result.failure(ResultCode.CODE_ERROR);
    }

    @Override
    public Result getUserById(Integer userId) {
        return Result.success(healthUserMapper.selectById(userId));
    }

    @Override
    public Result getSysUserList(UserDto userDto) {
        System.out.println("====="+userDto);
        List<HealthUser> sysUserList = healthUserMapper.getSysUserList(userDto, (userDto.getPageNum() - 1) * userDto.getPageSize(), userDto.getPageSize());
        int size = healthUserMapper.getSysUserList(userDto, null, null).size();
        return Result.success(new PageDto(userDto.getPageNum(),userDto.getPageSize(),size,sysUserList));
    }

    @Override
    public Result updateUser(HealthUser healthUser) {
        HealthUser user = healthUserMapper.selectOne(new QueryWrapper<HealthUser>().eq("user_phone", healthUser.getUserPhone()));
        if (user!=null && !user.getId().equals(healthUser.getId())){
            return Result.failure(ResultCode.DATA_ALREADY_EXISTED);
        }
        return Result.success(healthUserMapper.updateById(healthUser));
    }

    @Override
    public Result delUser(Integer[] ids) {
        return Result.success(healthUserMapper.deleteBatchIds(Arrays.asList(ids)));
    }

    @Override
    public Result resetPassword(Integer userId, String password) {
        HealthUser healthUser = healthUserMapper.selectById(userId);
        healthUser.setPassword(MD5Utils.getPWD(password));
        return Result.success(healthUserMapper.updateById(healthUser));
    }

    @Override
    public Result updatePassword(Integer userId,String oldPassword, String newPassword) {
        System.out.println(oldPassword+"==="+newPassword);
        HealthUser healthUser = healthUserMapper.selectById(userId);
        //比较旧密码输入是否正确
        if (!MD5Utils.getPWD(oldPassword).equals(healthUser.getPassword())){
            return Result.failure(ResultCode.DATA_STATUS_DELETE);
        }
        healthUser.setPassword(MD5Utils.getPWD(newPassword));
        return Result.success(healthUserMapper.updateById(healthUser));
    }

    @Override
    public Result updateImgUrl(Integer id, String imgUrl) {
        HealthUser healthUser = healthUserMapper.selectById(id);
        healthUser.setAvatar(imgUrl);
        if (healthUserMapper.updateById(healthUser)==1){
            return Result.success();
        }
        return Result.failure(ResultCode.DATA_STATUS_DELETE);
    }

    @Override
    public Result getUserByUserPhone(String userPhone) {
        return Result.success(healthUserMapper.selectOne(new QueryWrapper<HealthUser>().eq("user_phone",userPhone)));
    }

    @Override
    public void downLoad(Long[] ids, HttpServletResponse response) {
        //获取数据源
        List<HealthUser> healthUsers = healthUserMapper.selectBatchIds(Arrays.asList(ids));
        healthUsers.forEach(healthUser -> {
            healthUser.setUserRole(healthUser.getUserRole().equals("A")?"管理员":"普通用户");
        });
        ExcelUtil.download(response,healthUsers,HealthUser.class);
    }

    @Override
    public int importUsers(MultipartFile file) {
        List<HealthUser> healthUsers = parseUsersFromFile(file);
        Integer num=0;//数据导入数量
        for (HealthUser healthUser : healthUsers) {
            healthUser.setAvatar("https://edu-learn-bucket.oss-cn-hangzhou.aliyuncs.com/img_files/1712460465040.png");
            //md5密码加密
            healthUser.setPassword(MD5Utils.getPWD("123456"));
            healthUserMapper.insert(healthUser);
            num++;
        }
        return num;
    }

    private List<HealthUser> parseUsersFromFile(MultipartFile file) {
        // 实现文件解析逻辑，返回用户列表
        // 这里省略具体实现，因为取决于文件格式和所选的库
        List<HealthUser> users = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 假设文件是XLSX格式的
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个sheet

            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过标题行

                HealthUser user = new HealthUser();
                Cell usernameCell = row.getCell(0); // 假设用户名在第一列
                Cell phoneCell = row.getCell(1); // 假设密码在第二列
                phoneCell.setCellType(CellType.STRING);//设置单元格为字符串
                Cell roleCell = row.getCell(2); // 角色
                Cell remarksCell = row.getCell(3); // 角色

                if (usernameCell != null) {
                    System.out.println(usernameCell.getStringCellValue());
                    user.setUserName(usernameCell.getStringCellValue());
                }
                if (phoneCell != null) {
                    user.setUserPhone(phoneCell.getStringCellValue());
                }
                if (roleCell!=null){
                    String value = roleCell.getStringCellValue();
                    if (value.equals("管理员")){
                        user.setUserRole("A");
                    }else {
                        user.setUserRole("U");
                    }
                }
                if (remarksCell!=null){
                    user.setRemark(remarksCell.getStringCellValue());
                }
                //默认密码
                user.setPassword("123456");
                //默认头像
                user.setAvatar("https://edu-learn-bucket.oss-cn-hangzhou.aliyuncs.com/img_files/1712460465040.png");

                users.add(user);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件解析出错");
        }

        return users; // 返回null作为示例
    }
}




